<template>
  <div
    class="hello"
    style="
      width: 100%;
      display: flex;
      align-item: center;
      justify-content: center;
      margin-top: 50px;
      flex-direction: column;
    "
  >
    <section v-show="status === 'error'">{{ message }}</section>
    <section v-show="status === 'loading'">loading</section>
    <section
      v-show="status === 'successed'"
      style="
        width: 100%;
        display: flex;
        align-item: center;
        justify-content: center;
        flex-direction: column;
      "
    >
      <span>短链接 <a :href="shortUrl" target="__blank">{{shortUrl}}</a></span>
      <span>二维码：<i id="qrcode" ref="qrcode" /></span>
    </section>
  </div>
</template>

<script>
import QRCode from 'QRCode'
export default {
  name: "input-box",
  props: {
    msg: String,
  },
  data() {
    return {
      message: "",
      status: "",
      longUrl: "",
      shortUrl: "",
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.message = "";
      this.$bus.$on("sendLongUrl", (config) => {
        if (config.status) {
          this.longUrl =config.link;
          this.requestShortUrl();
        } else {
          this.status = "error";
          this.message = config.message;
        }
      });
    },
    requestShortUrl() {
      this.status = "loading";
      this.$refs.qrcode.innerHTML=""
      fetch("http://www.ggb.com:8000/api/url/shorten",{
        method:'post',
        headers:{
          'Content-type':'application/json',
          'Accept':'application/json'
        },
        body:JSON.stringify({
          longUrl:this.longUrl
        })
      }).then(res=>res.json()).then(res=>{
        this.shortUrl = res.shortUrl;
        this.status='successed'
        this.qrcode()
      })
    },
    qrcode(){
      new QRCode(this.$refs.qrcode,this.shortUrl)
    }
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
canvas {
   width: 100px !important;height:100px !important;
}
canvas img{
  width: 100px !important;height:100px !important;display:none !important;
}
</style>
